import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Master } from './master.entity';
import { CatsMember } from '../cats/cats.entity';

@Injectable()
export class MasterService {
  constructor(
    @InjectRepository(Master)
    private masterRepository: Repository<Master>,
    @InjectRepository(CatsMember)
    private catsRepository: Repository<CatsMember>,
  ) {}
  async create(params) {
    const { name, age, like } = params;
    let master = new Master();
    master.name = name;
    master.age = age;
    master.like = like;
    await this.masterRepository.save(master);
    return {
      msg: '添加成功!',
    };
  }
  async findAll(): Promise<Master[]> {
    let result = await this.masterRepository
      .createQueryBuilder()
      .leftJoinAndSelect('Master.catsMember', 'cats')
      .getMany();
    return result;
  }
  async updataCatMaster(params) {
    let msg = null;
    const { master_id, cats_id, cats_name } = params;
    let masterObj = await this.masterRepository.findOne({ id: master_id });
    masterObj == undefined && (msg = 'master_id不存在!');
    let catsObj = await this.catsRepository.findOne({
      id: cats_id,
      name: cats_name,
    });
    catsObj == undefined && (msg = 'cats不存在!');
    if (msg == null) {
      catsObj.master = masterObj; // 联接
      await this.catsRepository.save(catsObj);
      msg = '修改成功!';
    }

    return {
      msg,
    };
  }
}
